package com.ch.clinking.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.Utils.TimeUtil;
import com.ch.clinking.activity.AddOrderActivity;
import com.ch.clinking.activity.EditMerStockActivity;
import com.ch.clinking.bean.MerchandiseDto;
import com.ch.clinking.bean.Order;

import java.util.ArrayList;
import java.util.List;

public class SearchListAdapter extends ArrayAdapter<MerchandiseDto> implements Filterable {

    private Context context;
    private List<MerchandiseDto> originalMerchandiseDtos; // 原始数据
    private List<MerchandiseDto> filteredMerchandiseDtos; // 过滤后的数据
    boolean color = true;

    public SearchListAdapter(@NonNull Context context, int resource, @NonNull List<MerchandiseDto> merchandises) {
        super(context, resource, merchandises);
        this.context = context;
        this.originalMerchandiseDtos  = new ArrayList<>(merchandises);
        this.filteredMerchandiseDtos  = new ArrayList<>(merchandises);  // 将原始数据转换为可修改的 ArrayList
    }

    @Override
    public int getCount() {
        return filteredMerchandiseDtos.size();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_spu_layout, parent, false);
        }

        if (position >= 0 && position < filteredMerchandiseDtos.size()) {

            MerchandiseDto merchandise = filteredMerchandiseDtos.get(position);

            // Lookup view for data population
            ImageView merImg = convertView.findViewById(R.id.list_spu_img);

            // 设置默认占位图片
            Glide.with(context)
                    .load(R.drawable.appicon)
                    .into(merImg);

            // 加载图片
            Glide.with(context)
                    .load(OkHttpUtil.getInstance().getIMG_URL() + merchandise.getFirstImage())
                    .placeholder(R.drawable.appicon)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)  // 缓存策略：缓存原始图片和转换后的图片
                    .thumbnail(0.5f)  // 缩略图大小
                    .error(R.drawable.appicon)
                    .into(merImg);

            // 执行异步任务加载图片
//        new DownloadImage(merImg).execute(OkHttpUtil.getInstance().getIMG_URL()+merchandise.getFirstImage());
            TextView merTitle = convertView.findViewById(R.id.list_spu_title);
            TextView merSKCId = convertView.findViewById(R.id.list_skc_id);
            TextView merSPUId = convertView.findViewById(R.id.list_spu_id);
            TextView productNum = convertView.findViewById(R.id.list_SKC_product_num);
//        TextView copySpu = view.findViewById(R.id.copy_spu_button);
//        TextView copySkc = view.findViewById(R.id.copy_skc_button);
            TableLayout tableLayout = convertView.findViewById(R.id.stock_table);
            ViewGroup list_mer_item_container = convertView.findViewById(R.id.list_mer_item_container);
            Button makeOrder = convertView.findViewById(R.id.oder_make);
            LinearLayout container = convertView.findViewById(R.id.mer_order_circle_tag_container);
            merTitle.setText(merchandise.getTitle());
            merSKCId.setText(merchandise.getSkcId());
            merSPUId.setText(merchandise.getSpuId());
            productNum.setText(merchandise.getProductNumber());


            // 清空表格内容
            tableLayout.removeAllViews();

            // 动态生成表格内容
            getSize(merchandise, tableLayout);


//        getOrderInfoTagList(merchandise.getSkcId(), holder.circleContainer);

            // 动态添加圆圈
            addCircleTextViews(merchandise.getOrderList(), container);



            list_mer_item_container.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, EditMerStockActivity.class);
                    intent.putExtra("skcId", merchandise.getSkcId());
                    context.startActivity(intent);
                }
            });

            makeOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, AddOrderActivity.class);
                    intent.putExtra("skcId", merchandise.getSkcId());
                    context.startActivity(intent);
                }
            });

//            tableLayout.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    Intent intent = new Intent(context, EditMerStockActivity.class);
//                    intent.putExtra("merchandise", merchandise);
//                    context.startActivity(intent);
//                }
//            });

        }



        return convertView;
    }

    @SuppressLint("SetTextI18n")
    private void getSize(MerchandiseDto merchandise, TableLayout tableLayout) {
        color = true;
        TableRow sizeRow = new TableRow(context);
        TableRow stockRow = new TableRow(context);
        sizeRow.setPadding(0, 0, 0, 0);
        stockRow.setPadding(0, 0, 0, 0);
        TableRow.LayoutParams editTextParams = new TableRow.LayoutParams(120, TableRow.LayoutParams.MATCH_PARENT);
        editTextParams.gravity = Gravity.CENTER;

        if (merchandise.isActivate_XXS()) {
            TextView size = new TextView(context);
            size.setText("XXS");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XXS()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_XS()) {
            TextView size = new TextView(context);
            size.setText("XS");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XS()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_S()) {
            TextView size = new TextView(context);
            size.setText("S");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_S()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_M()) {
            TextView size = new TextView(context);
            size.setText("M");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_M()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_L()) {
            TextView size = new TextView(context);
            size.setText("L");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_L()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_XL()) {
            TextView size = new TextView(context);
            size.setText("XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_XXL()) {
            TextView size = new TextView(context);
            size.setText("XXL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_XXL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_0XL()) {
            TextView size = new TextView(context);
            size.setText("0XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_0XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_1XL()) {
            TextView size = new TextView(context);
            size.setText("1XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_1XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_2XL()) {
            TextView size = new TextView(context);
            size.setText("2XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_2XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_3XL()) {
            TextView size = new TextView(context);
            size.setText("3XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_3XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_4XL()) {
            TextView size = new TextView(context);
            size.setText("4XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_4XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_5XL()) {
            TextView size = new TextView(context);
            size.setText("5XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_5XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }
        if (merchandise.isActivate_Plus_6XL()) {
            TextView size = new TextView(context);
            size.setText("6XL");
            TextView stock = new TextView(context);
            stock.setText(Integer.toString(merchandise.getInHouseStock_Plus_6XL()));
            setTableLayout(size, stock, sizeRow, stockRow, editTextParams);
        }

        tableLayout.addView(sizeRow);
        tableLayout.addView(stockRow);
    }

    private void setTableLayout(TextView size, TextView stock, TableRow sizeRow, TableRow stockRow, TableRow.LayoutParams editTextParams) {
        size.setLayoutParams(editTextParams);
        stock.setLayoutParams(editTextParams);
        size.setBackgroundColor(getCellColor());
        stock.setBackgroundColor(getCellColor());
        if (color) {
            color = false;
        } else {
            color = true;
        }
        size.setWidth(120);
        stock.setWidth(120);
        size.setPadding(0, 0, 0, 0);
        stock.setPadding(0, 0, 0, 0);
        size.setGravity(Gravity.CENTER);
        stock.setGravity(Gravity.CENTER);
        sizeRow.addView(size);
        stockRow.addView(stock);
    }

    private int getCellColor() {
        if (color) {
            return Color.parseColor("#E7E7E7"); // 偶数索引
        } else {
            return Color.parseColor("#FFFFFF"); // 奇数索引
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void addCircleTextViews(List<Order> values, LinearLayout circleContainer) {
        circleContainer.removeAllViews();
        int diameter = 70;  // 圆形的直径，可以根据需要调整

        for (Order order : values) {
            TextView textView = new TextView(context);
            textView.setText(order.getCreatedTime().substring(8, 10));
            textView.setTextColor(context.getResources().getColor(android.R.color.white));
            textView.setTextSize(11);

            Log.d("OrderTag", "refreshMerchandiseList"+order.getCreatedTime());

            long day = (int) TimeUtil.getDayNum(order.getCreatedTime());



            // 设置圆形背景
            GradientDrawable background = new GradientDrawable();

            // 背景颜色
            if (day <= 3) {
                background.setColor(context.getResources().getColor(R.color.order_state_yes));
            } else if (day <= 5) {
                background.setColor(context.getResources().getColor(R.color.order_state_orange));
            } else if (day <= 7) {
                background.setColor(context.getResources().getColor(R.color.order_state_no_bg));
            } else {
                background.setColor(context.getResources().getColor(R.color.black));
            }

            background.setShape(GradientDrawable.OVAL); // 圆形
            background.setSize(diameter, diameter); // 设置宽度和高度相等
            textView.setBackground(background);

            // 设置内边距
            int padding = 10;
            textView.setPadding(padding, padding, padding, padding);

            // 设置TextView的宽度和高度相等
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(diameter, diameter);
            params.setMargins(10, 0, 10, 0); // 设置间距
            textView.setLayoutParams(params);

            // 设置TextView的重力居中
            textView.setGravity(Gravity.CENTER);

            circleContainer.addView(textView);
        }
    }

    @NonNull
    @Override
    public Filter getFilter() {
        return new MerchandiseDtoFilter(this, originalMerchandiseDtos);
    }

    private static class MerchandiseDtoFilter extends Filter {

        private final SearchListAdapter adapter;
        private final List<MerchandiseDto> originalList;

        private MerchandiseDtoFilter(SearchListAdapter adapter, List<MerchandiseDto> originalList) {
            super();
            this.adapter = adapter;
            this.originalList = new ArrayList<>(originalList);
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<MerchandiseDto> filteredList = new ArrayList<>();

            if (constraint == null || constraint.length() == 0) {
                // 没有搜索内容，显示原始列表
                filteredList.addAll(originalList);
            } else {
                // 根据搜索内容筛选列表
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (MerchandiseDto merchandise : originalList) {
                    if (merchandise.getProductNumber().toLowerCase().contains(filterPattern)) {
//                    if (merchandise.getTitle().toLowerCase().contains(filterPattern)) {
                        filteredList.add(merchandise);
                    }
                }
            }

            results.values = filteredList;
            results.count = filteredList.size();
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            adapter.filteredMerchandiseDtos.clear();
            if (results.values != null) {
                adapter.filteredMerchandiseDtos.addAll((List<MerchandiseDto>) results.values);
            }
            adapter.notifyDataSetChanged();
        }
    }

}
